package com.swapper.markdown;

import com.swapper.markdown.elements.MarkdownHeadLine;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Stack;

public class MarkdownReader {


  public static void main(String[] args) throws IOException {
    StringReader stringReader = new StringReader("### abc\n####asd");
    MarkdownReader markdownReader = new MarkdownReader(stringReader);
    markdownReader.parseLine();
  }


  private final BufferedReader reader;
  private int cursor;
  private int size;
  private final char[] buffer = new char[BUFFER_SIZE];
  private static final int BUFFER_SIZE = 8192;
  private static final int ROLLBACK_SIZE = 32;

  public MarkdownReader(Reader in) {
    reader = new BufferedReader(Objects.requireNonNull(in));
  }


  private int buffered() throws IOException {
    if (size == 0) {
      size = reader.read(buffer);
      if (size == -1) {
        throw new EOFException("The input stream is empty.");
      }
    } else {
      size = reader.read(buffer);
    }
    return size;
  }

  private int skipLineWhitespace() throws IOException {
    int number = 0;
    while (true) {
      if (cursor >= size) {
        buffered();
      }
      char temp = buffer[cursor++];
      if (temp == ' ' || temp == '\t') {
        ++number;
      } else {
        break;
      }
    }
    return number;
  }

  private void parseLine2() {

  }


  private void parseLine() throws IOException {
    String line = reader.readLine();
    if (line == null || line.isEmpty()) {
      return;
    }
    int length = line.length();
    int frontWhitespaces = 0;
    for (; frontWhitespaces < length; ++frontWhitespaces) {
      if (!Character.isWhitespace(line.charAt(frontWhitespaces))) {
        break;
      }
    }
    if (frontWhitespaces == length - 1) {
      return;
    }
    int backWhitespaces = 0;
    for (int i = length - 1; i >= frontWhitespaces; --i) {
      if (Character.isWhitespace(line.charAt(i))) {
        ++backWhitespaces;
      } else {
        break;
      }
    }
    char ch = line.charAt(frontWhitespaces);
    if (ch == '#') {
      int level = 1;
      int headBegin = frontWhitespaces + 1;
      for (; headBegin < length; ++headBegin) {
        if (line.charAt(headBegin) == '#') {
          if (++level == 6) {
            ++headBegin;
            break;
          }
        } else {
          break;
        }
      }
      for (; headBegin < length; ++headBegin) {
        if (!Character.isWhitespace(line.charAt(headBegin))) {
          break;
        }
      }
      System.out.println(new MarkdownHeadLine(level, line.substring(headBegin)));
      parseLine();
      return;
    }
    if (ch == '-' || ch == '+' || ch == '*') {

    }
  }
}
